package com.wangchao523.util.servletUtil;

import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import com.wangchao523.util.PropertiesUtil;

/**
 * 项目启动时加载
 * 1、log4j初始化配置
 * 2、action类简称对应全称配置
 * @author corey
 */
@SuppressWarnings("serial")
public class InitServlet extends HttpServlet {
	
	Logger log = Logger.getLogger(this.getClass().getName());
	
	public static Properties actionProperties = null;	//action映射文件的参数集合
	public static String rootPath = "";	//当前web应用的真实的根目录
	public static String vmPath = "";		//vm页面文件夹路径
	public static String db4oPath = "";	//db4o数据库文件路径
	
	@Override
	public void init() throws ServletException {
		rootPath =  getServletContext().getRealPath("/");//获取当前web应用的真实的根目录
		
		String log4jPath = getInitParameter("log4j");//从web.xml中读取初始化参数中的Log4J配置文件的位置
		if(log4jPath != null) {
			PropertyConfigurator.configure(rootPath + log4jPath); //读取Log4j配置文件，配置Log4j环境
			log.info("加载log4j配置文件完成");
		} 
		
		//初始化action类的配置
		actionProperties = getProperties("actionProperties");
		
		//初始化vm文件夹路径
		log.info("初始化其他配置常量");
		vmPath = getParameter("vmPath", "WEB-INF/vm/");
		
		db4oPath = getParameter("db4o", rootPath + "sms.db4o");
	}
	
	/**
	 * 初始化配置参数
	 * @param para
	 * @param defaultPara
	 * @return
	 */
	private String getParameter(String para, String defaultPara){
		String parameter = getInitParameter(para);
		if(parameter == null || "".equals(parameter)) { 
			parameter = defaultPara;
		}
		return parameter;
	}
	
	private Properties getProperties(String filePath){
		String actionPath = getInitParameter("actionProperties");
		Properties properties = null;
		if(actionPath != null) { 
			properties = PropertiesUtil.getPropertiesObj(rootPath + actionPath);
			log.info("初始化" + filePath + "配置文件完成");
		}else{
			properties = new Properties();
			log.error("读取" + filePath + "配置文件参数错误");
		}
		return properties;
	}

}
